package com.zhixing.common.config;

import cn.hutool.core.util.ObjectUtil;
import com.zhixing.common.annotation.Driver;
import com.zhixing.common.annotation.Passenger;
import com.zhixing.common.domain.enums.Role;
import com.zhixing.common.exception.ZhixingException;
import com.zhixing.common.utils.UserContext;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import static com.zhixing.common.domain.enums.HttpStatus.ROLE_NOT_CONFORM;

@Aspect
@Component
public class RoleAspect {

    @Before("@annotation(com.zhixing.common.annotation.Passenger) || @annotation(com.zhixing.common.annotation.Driver)")
    public void authRole(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Role role = UserContext.getUserInfo().getRole();
        if ((ObjectUtil.isEmpty(method.getAnnotation(Passenger.class)) && role == Role.PASSENGER) ||
                (ObjectUtil.isEmpty(method.getAnnotation(Driver.class)) && role == Role.DRIVER)) {
            throw new ZhixingException(ROLE_NOT_CONFORM);
        }
    }
}
